package com.tmsps.ne4Weixin.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tmsps.ne4Weixin.beans.UserTag;
import com.tmsps.ne4Weixin.config.WxConfig;
import com.tmsps.ne4Weixin.utils.HttpClient;

/**
 * 
 * @author zhangwei 396033084@qq.com
 */
public class TagAPI extends BaseAPI {
	private static String TAG_ADD = BaseURL.concat("/cgi-bin/tags/create?access_token=%s");
	private static String TAG_EDIT = BaseURL.concat("/cgi-bin/tags/update?access_token=%s");
	private static String TAG_DELETE = BaseURL.concat("/cgi-bin/tags/delete?access_token=%s");
	private static String TAG_LIST = BaseURL.concat("/cgi-bin/tags/get?access_token=%s");

	public TagAPI(WxConfig config) {
		super(config);
	}

	public UserTag addTag(String tag) {
		JSONObject tagJson = new JSONObject();
		tagJson.put("name", tag);
		JSONObject jo = new JSONObject();
		jo.put("tag", tagJson);
		String result = HttpClient.postJson(String.format(TAG_ADD, config.getAccessToken()), jo.toJSONString());
		JSONObject obj = JSONObject.parseObject(result);
		return JSONObject.parseObject(obj.getJSONObject("tag").toJSONString(), UserTag.class);
	}

	public JSONObject deleteTag(int id) {
		JSONObject tagJson = new JSONObject();
		tagJson.put("id", id);
		JSONObject jo = new JSONObject();
		jo.put("tag", tagJson);
		return JSONObject.parseObject(HttpClient.postJson(String.format(TAG_DELETE, config.getAccessToken()), jo.toJSONString()));
	}

	public JSONObject editTag(int id, String name) {
		JSONObject tagJson = new JSONObject();
		tagJson.put("id", id);
		tagJson.put("name", name);
		JSONObject jo = new JSONObject();
		jo.put("tag", tagJson);
		return JSONObject.parseObject(HttpClient.postJson(String.format(TAG_EDIT, config.getAccessToken()), jo.toJSONString()));
	}

	public JSONArray listTag() {
		JSONObject result = JSON.parseObject(HttpClient.httpGet(String.format(TAG_LIST, config.getAccessToken()), null));
		return result.getJSONArray("tags");
	}
}
